package cn.happiness.frog.skill.rest;

import cn.happiness.frog.skill.service.SongService;
import cn.happiness.frog.skill.util.Json;
import cn.happiness.frog.skill.xiaoai.Request;
import cn.happiness.frog.skill.xiaoai.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@AllArgsConstructor
public class PianoSkillResource {
	private final SongService songService;

	@PostMapping(path = "/xiaoai/piano-playing")
	public ResponseEntity<Response> playing(@RequestBody Request request) throws JsonProcessingException {
		log.info("playing: {} ", Json.mapper.writeValueAsString(request));
		Response response = new Response();
		String intentName = request.getIntentName();
		if ("Mi_Welcome".equals(intentName)) {
			return ResponseEntity.ok(response.speakReply("欢迎使用天天钢琴，可以练习钢琴跟弹哟，您要跟弹哪首曲子?"));
		} else if ("playing".equals(intentName)) {
			String text = request.getQuery();
			if (text == null) {
				return ResponseEntity.ok(response.speakReply("请说你要跟弹的曲子，比如小星星"));
			} else {
				String songURL = songService.findSongURL(text);
				if (songURL == null) {
					return ResponseEntity.ok(response.speakReply(String.format("没有找到%s这首曲子，请换一首?", text)));
				}
				return ResponseEntity.ok(response.ttsReply("好的").audioReply(songURL));
			}
		} else if ("Mi_Exit".equals(intentName)) {
			return ResponseEntity.ok(response.exit("再见"));
		}
		return ResponseEntity.ok(response.notUnderstand());
	}
}
